import { message } from "ant-design-vue";
import axios from "axios";
import type { AxiosRequestConfig } from 'axios'
import qs from 'qs'
import storage from "@/storage";
import { StorageConst } from '../constant'
import Config from "@/config";
import { useTagStore } from "@/stores/tag";
import { router } from "@/router";

axios.defaults.baseURL = "";
(axios.defaults.headers as any)["Content-Type"] = "application/json";

/**
 * @description request 拦截器
 */
axios.interceptors.request.use(request => {
  const { headers } = request;
  
  if (headers) {

    if ((headers["Content-Type"] as any).indexOf('x-www-form-urlencoded') != -1) {
      request.data = typeof request.data == 'object' ? qs.stringify(request.data) : request.data;
    }

    // 增加multipart/form-data处理
    if ((headers["Content-Type"] as any).indexOf('multipart/form-data') != -1) {
      const data = new FormData();

      for (const key in request.data) {
        const value = request.data[key];
        data.append(key, value);
      }

      request.data = data;
    }

    // 设置token
    const token = storage.getItem(StorageConst.Token) as string;

    if (token) {
      headers[Config.HEADER_TOKEN_KEY] = token;
    }
  }

  return request;
});
/**
 * @description response 拦截器  
 */
axios.interceptors.response.use(
  // 响应
  async response => {
    const { config } = response;
    let code = 0;
    let msg = '';

    // 当为下载文件时直接返回
    if (config.responseType == 'blob') {
      return Promise.resolve(response.data);
    }
    code = response.data.code || response.data.statusCode;
    msg = response.data.message || response.data.statusMsg;

    if (code === 401) {
      // 清除token
      storage.removeItem(StorageConst.Token);
      // window.location.href = "/authentication";
      // 清空全部路由
      useTagStore().clearTagRouteAll();
      router.replace("/authentication");
      message.error(msg || "登录失效，请重新登录");
      return Promise.reject(response.data);
    } else if (code != 200) {
      if (!config.hideToast) {
        message.error(msg || "错误！服务端未提供错误信息 错误代码：" + code);
      }

      // 如配置了重试直接重试
      if (config.repeat) {
        return await config.repeat(response) ? axios(config) : Promise.reject(response.data);
      }

      return Promise.reject(response.data);
    } else {
      return Promise.resolve(response.data);
    }
  },
  // 访问出错
  error => {
    const config = error.config as AxiosRequestConfig;
    config && !config.hideToast && error && message.error(error.message);
    return Promise.reject(error);
  }
);